package com.kfh.ybracelet.my;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.adapter.FamilyAdapter;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.Family;
import com.kfh.ybracelet.bean.FamilyResultInfo;
import com.kfh.ybracelet.bean.UpdateFamily;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.DensityUtil;
import com.kfh.ybracelet.utils.LogUtil;
import com.kfh.ybracelet.widget.ActionSheetDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 家庭详情页面
 * Created by Administrator on 2015/11/6.
 */
public class FamilyDetailsActivity extends BaseActivity implements View.OnClickListener{

    private ImageView iv_left;
    private ImageView iv_counts;

//    private TextView tv_family;
    private TextView tv_home_condition;
    private TextView tv_family_adress;
    private TextView tv_account_type;
    private TextView tv_account_adress;
    private TextView tv_title;
    private Intent mIntent;
    private String childID;
    private SwipeMenuListView lv_family;
    private List<Family> families = new ArrayList<Family>();
    private FamilyAdapter familyAdapter;
    private Dialog addressDialog;
    private EditText et_address;
    private EditText et_card_address;
    private Dialog cardAddressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_family_details);
//        mApplication.addActivity(this);
        childID = getIntent().getStringExtra("childId");

        init();

    }

    @Override
    protected void onResume() {
        super.onResume();

        //获取家庭信息
        getFamilyInfo();

    }

    /**
     * 获取家庭信息
     */
    private void getFamilyInfo() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("id", childID);

        HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT + Constant.CHILDINFO,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            FamilyResultInfo resultInfo = JSONObject.parseObject(str, FamilyResultInfo.class);

//                            if (Constant.STATUS_SUCCESS == resultInfo.code) {

                                tv_home_condition.setText(resultInfo.data.houseType);//房产情况
                                tv_family_adress.setText(resultInfo.data.address);//地址
                                tv_account_type.setText(resultInfo.data.hukouType);//户口类型
                                tv_account_adress.setText(resultInfo.data.hukouAddress);//户口地址

                                families = resultInfo.data.family;

                                if (families != null) {
                                    familyAdapter.setFamilies(families);
                                    familyAdapter.notifyDataSetChanged();
                                }

//                            } else {
//                                showToast(Constant.showErrorMsg(resultInfo.code, FamilyDetailsActivity.this));
//                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);

    }

    private void init() {

        iv_left = (ImageView) findViewById(R.id.iv_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
//        tv_family = (TextView) findViewById(R.id.tv_family);
        iv_counts = (ImageView) findViewById(R.id.iv_counts);


        tv_title.setText(getResources().getString(R.string.family_detail));

        lv_family = (SwipeMenuListView) findViewById(R.id.lv_family);

        familyAdapter = new FamilyAdapter(this, families);
        lv_family.setAdapter(familyAdapter);

        //滑动删除
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {

                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());

                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));

                deleteItem.setWidth(DensityUtil.dip2px(FamilyDetailsActivity.this, 80));

                deleteItem.setIcon(R.mipmap.ic_delete);

                menu.addMenuItem(deleteItem);

            }
        };

        lv_family.setMenuCreator(creator);

        View footView = View.inflate(this, R.layout.layout_foot_family_detail, null);

        lv_family.addFooterView(footView);

        lv_family.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
//                         delete
//                        LogUtil.e("tag", "=======shanchu=======" + position);

                        if (families!=null && families.size()>0) {
                            families.remove(position);
                            updateFamilyInfo("", "", "", "", families);
                        }

                        break;
                }

                return false;

            }
        });

        tv_home_condition = (TextView) footView.findViewById(R.id.tv_home_condition);
        tv_family_adress = (TextView) footView.findViewById(R.id.tv_family_adress);
        tv_account_type = (TextView) footView.findViewById(R.id.tv_account_type);
        tv_account_adress = (TextView) footView.findViewById(R.id.tv_account_adress);

        RelativeLayout rl_home_condition = (RelativeLayout) footView.findViewById(R.id.rl_home_condition);
        RelativeLayout rl_adress = (RelativeLayout) footView.findViewById(R.id.rl_adress);
        RelativeLayout rl_account_type = (RelativeLayout) footView.findViewById(R.id.rl_account_type);
        RelativeLayout rl_account_adress = (RelativeLayout) footView.findViewById(R.id.rl_account_adress);

        iv_left.setOnClickListener(this);
        iv_counts.setOnClickListener(this);

        rl_home_condition.setOnClickListener(this);
        rl_adress.setOnClickListener(this);
        rl_account_type.setOnClickListener(this);
        rl_account_adress.setOnClickListener(this);

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()){

            case R.id.iv_left:
                finish();
                break;

            case R.id.iv_counts: //添加家庭成员

                LogUtil.e("tag", "level===" + getIntent().getIntExtra("level", 0));

                if (getIntent().getIntExtra("level", 0) == Constant.POWER_ADMIN) {
                    //是管理员才可以添加家庭成员
                    mIntent = new Intent(this, AddFamilyDetailsActivity.class);
                    mIntent.putExtra("childID", childID);
                    mIntent.putExtra("families", (Serializable)families);
                    startActivity(mIntent);

                } else {
                    showToast("无权限");
                }

                break;

            case R.id.rl_home_condition: //房产情况

                showHomeCondition();

                break;

            case R.id.rl_adress: //地址

                updateAddress();

                break;

            case R.id.rl_account_type: //户口类型

                showCardCondition();

                break;

            case R.id.rl_account_adress: //户口地址

                updateCardAddress();

                break;

            case R.id.tv_cancle:

                if (addressDialog!=null && addressDialog.isShowing())
                    addressDialog.dismiss();

                break;
            case R.id.tv_card_cancle:

                if (cardAddressDialog!=null && cardAddressDialog.isShowing())
                    cardAddressDialog.dismiss();

                break;

            case R.id.tv_sure: //更改地址

                if (addressDialog!=null && addressDialog.isShowing())
                    addressDialog.dismiss();

                updateFamilyInfo(et_address.getText().toString().trim(), "", "", "", null);

                break;
            case R.id.tv_card_sure: //更改户口地址

                if (cardAddressDialog!=null && cardAddressDialog.isShowing())
                    cardAddressDialog.dismiss();

                updateFamilyInfo("", "", "", et_card_address.getText().toString().trim(), null);

                break;

        }

    }

    /**
     * 房产情况
     */
    public void showHomeCondition() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("自有", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 自有
                                updateFamilyInfo("", "自有", "", "", null);

                            }

                        })
                .addSheetItem("租赁", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 租赁
                                updateFamilyInfo("", "租赁", "", "", null);

                            }
                        }).show();

    }

    /**
     * 户口类型
     */
    public void showCardCondition() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("非农", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 非农
                                updateFamilyInfo("", "", "非农", "", null);

                            }

                        })
                .addSheetItem("农业", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                 农业
                                updateFamilyInfo("", "", "农业", "", null);

                            }
                        }).show();

    }


    /**
     * 更改地址
     */
    private void updateAddress() {

        addressDialog = new Dialog(this, R.style.no_title);
// new Dialog();
        addressDialog.setCancelable(true);
        addressDialog.setCanceledOnTouchOutside(true);
        addressDialog.show();
        addressDialog.setContentView(R.layout.dialog_add_address);
//        whiteListDialog.getWindow().setContentView(R.layout.dialog_add_white_list);
//        whiteListDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        changeScreen(0.5f);

        addressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                changeScreen(1.0f);
            }
        });

        et_address = (EditText) addressDialog.findViewById(R.id.et_address);
        TextView tv_cancle = (TextView) addressDialog.findViewById(R.id.tv_cancle);
        TextView tv_sure = (TextView) addressDialog.findViewById(R.id.tv_sure);

        tv_sure.setOnClickListener(this);
        tv_cancle.setOnClickListener(this);

    }

    /**
     * 更改户口地址
     */
    private void updateCardAddress() {

        cardAddressDialog = new Dialog(this, R.style.no_title);
// new Dialog();
        cardAddressDialog.setCancelable(true);
        cardAddressDialog.setCanceledOnTouchOutside(true);
        cardAddressDialog.show();
        cardAddressDialog.setContentView(R.layout.dialog_add_card_address);
//        whiteListDialog.getWindow().setContentView(R.layout.dialog_add_white_list);
//        whiteListDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        changeScreen(0.5f);

        cardAddressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                changeScreen(1.0f);
            }
        });

        et_card_address = (EditText) cardAddressDialog.findViewById(R.id.et_card_address);
        TextView tv_card_cancle = (TextView) cardAddressDialog.findViewById(R.id.tv_card_cancle);
        TextView tv_card_sure = (TextView) cardAddressDialog.findViewById(R.id.tv_card_sure);

        tv_card_sure.setOnClickListener(this);
        tv_card_cancle.setOnClickListener(this);

    }

    private void changeScreen(float f) {

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        lp.dimAmount = f;
        getWindow().setAttributes(lp);

    }

    /**
     * 更新家庭信息
     *
     * @param address 地址
     * @param houseType 房产情况
     * @param hukouAddress 户口地址
     * @param hukouType 户口类型
     *
     */
    private void updateFamilyInfo(final String address, final String houseType, final String hukouType, final String hukouAddress, final List<Family> families) {

        UpdateFamily updateFamily = new UpdateFamily();
        updateFamily.token = sp.getString(Constant.TOKEN, "");
        updateFamily.address = address;
        updateFamily.houseType = houseType;
        updateFamily.hukouType = hukouType;
        updateFamily.hukouAddress = hukouAddress;
        updateFamily.id = childID;

//        UpdateFamily.Family family = updateFamily.new Family();
//        family.name = et_name.getText().toString().trim();
//        family.phoneNum = et_contact_way.getText().toString().trim();
//        family.workUnit = et_unit.getText().toString().trim();

        if (families == null)
        updateFamily.family = new ArrayList<Family>();
        else
        updateFamily.family = families;
//        updateFamily.family.add(family);

        HttpUtil.setPostRequest("添加中...", this, Constant.WEB_ROOT + Constant.UPDATEFAMILYINFO,
                JSONObject.toJSONString(updateFamily), getClass().getName(), new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    org.json.JSONObject result = new org.json.JSONObject(str);

//                    if (result.getInt("code") == Constant.STATUS_SUCCESS) {

                        showToast("更新成功");

                        if (!CommonUtils.isNull(address)) {

                            tv_family_adress.setText(address);

                        } else if (!CommonUtils.isNull(houseType)) {

                            tv_home_condition.setText(houseType);

                        } else if (!CommonUtils.isNull(hukouType)) {

                            tv_account_type.setText(hukouType);

                        } else if (!CommonUtils.isNull(hukouAddress)) {

                            tv_account_adress.setText(hukouAddress);
                        }

                        if (families != null) {
                            FamilyDetailsActivity.this.families = families;
                            familyAdapter.setFamilies(families);
                            familyAdapter.notifyDataSetChanged();
//                            familyAdapter = new FamilyAdapter(this, families);
//                            lv_family.n
                        }

//                    } else
//                        showToast(Constant.showErrorMsg(result.getInt("code"), FamilyDetailsActivity.this));

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, null);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mApplication.cancelPendingRequests(getClass().getName());
    }

}
